<?php

namespace Lib;

class Auth {

	public static function check() {
		return \Session::get('USER_ID') !== NULL;
	}

	public static function get_user($id = 0) {
		if ($id == 0) {
			return json_decode(json_encode(\Session::get('USER')));
		}
		else {
			return \Model_User::find_one_by_id($id);
		}
	}

	public static function get_user_id() {
		return \Session::get('USER_ID');
	}

	public static function login($username = '', $password = '', $remember = false) {
		if ($username !== '' && $password !== '') {
			$user = \Model_User::query()
				->where('username', $username)
				->or_where('email', $username)
				->get_one();

			if ($user) {
				if ($user->password == \Helper\Security::hash($password)) {
					// save session
					\Session::set('USER_ID', $user->id);
					\Session::set('USER', $user->to_array());
					return true;
				}
			}
		}

		return false;
	}

	public static function logout() {
		\Session::destroy();
	}

	public static function has_role($role = '') {
		$user = static::get_user();
		return in_array($role, explode(',', $user->roles));
	}

	public static function member($type = 'ADMIN') {
		$user = static::get_user();
		return $user->type == $type;
	}

}
